package com.tianyu.inspection.common.model;

import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianyu.inspection.entity.model.QueryMo;

import java.util.Map;
import java.util.Objects;

/**********************************
 * @Author YSW
 * @Description
 * @Date 2020.08.20 - 14:50
 **********************************/

public class PageModel {
	/**
	 * 获取分页数据
	 * @param queryMo
	 * @param mapper
	 * @return
	 */
	public static <T> IPage<T> getModelPage(QueryMo queryMo, BaseMapper<T> mapper) {
		return getModelPage(new QueryWrapper<T>(),queryMo,mapper);
	}


	/**
	 * 获取分页数据
	 * @param wrapper
	 * @param mapper
	 * @return
	 */
	public static <T> IPage<T> getModelPage(QueryWrapper<T> wrapper,Page<T> page, BaseMapper<T> mapper) {
		return mapper.selectPage(page,wrapper);
	}


	/**
	 * 获取分页数据
	 * @param queryMo
	 * @param mapper
	 * @return
	 */
	public static <T> IPage<T> getModelPage(QueryWrapper<T> wrapper,QueryMo queryMo, BaseMapper<T> mapper) {
		Page<T> page;
		if (Objects.nonNull(queryMo)){
			page = new Page<>(queryMo.getPageNum(), queryMo.getPageSize());
			wrapper.allEq(queryMo.getEqMap());
			String ascParams = queryMo.getAscParams();
			String descParams = queryMo.getDescParams();
			Map<String, JSONArray> inMap = queryMo.getInMap();
			Map<String, String> likeMap = queryMo.getLikeMap();
			if (Objects.nonNull(ascParams) && !Objects.equals(ascParams, "")){
				wrapper.orderByAsc(ascParams);
			}
			if (Objects.nonNull(descParams) && !Objects.equals(descParams, "")){
				wrapper.orderByDesc(descParams);
			}
			if (Objects.nonNull(inMap)){
				inMap.forEach(wrapper::in);
			}
			if (Objects.nonNull(likeMap)){
				likeMap.forEach(wrapper::like);
			}
		}else {
			page = new Page<>(1, -1);
		}
		return mapper.selectPage(page,wrapper);
	}

	/**
	 * 获取分页数据
	 * @param queryMo
	 * @return
	 */
	public static <T> QueryWrapper<T> getModelWrapper(QueryMo queryMo) {
		QueryWrapper<T> wrapper = new QueryWrapper<>();
		if (Objects.nonNull(queryMo)){
			wrapper.allEq(queryMo.getEqMap());
			String ascParams = queryMo.getAscParams();
			String descParams = queryMo.getDescParams();
			if (Objects.nonNull(ascParams) && !Objects.equals(ascParams, "")){
				wrapper.orderByAsc(ascParams);
			}
			if (Objects.nonNull(descParams) && !Objects.equals(descParams, "")){
				wrapper.orderByDesc(descParams);
			}
		}
		return wrapper;
	}

	/**
	 * 获取分页数据
	 * @param queryMo
	 * @return
	 */
	public static <T> IPage<T> getModelPage(QueryMo queryMo) {
		Page<T> page;
		if (Objects.nonNull(queryMo)){
			page = new Page<>(queryMo.getPageNum(), queryMo.getPageSize());
		}else {
			page = new Page<>(1, -1);
		}
		return page;
	}
}
